package com.gframework.boot.mvc.filter;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import com.gframework.boot.mvc.controller.protocal.basic.ServerResponse;
import com.gframework.util.JsonUtils;

/**
 * 默认的rest请求重定向返回结果拦截器.
 * <p>将重定向路径封装到{@link ServerResponse}中返回，同时设置到 {@value #LOCATION_HEADRE_NAME} 请求头中。
 * 
 * @since 1.0.0
 * @author Ghwolf
 * 
 * @see RestRequestHandleFilter
 * @see RestRedirectResponseInterceptor
 */
@ConditionalOnMissingBean(RestRedirectResponseInterceptor.class)
public class DefaultRestRedirectInterceptor implements RestRedirectResponseInterceptor{
	private static final Logger logger = LoggerFactory.getLogger(DefaultRestRedirectInterceptor.class);
	
	public DefaultRestRedirectInterceptor(){
		logger.info("====> 已启用 DefaultRestRedirectInterceptor 重定向拦截器，以便于将其转换为rest响应结果返回。同时也会将location值保存到{}响应头中，可通过ajax获取！",
				LOCATION_HEADRE_NAME);
	}
	
	/**
	 * rest风格请求，重定向地址存的响应头名称
	 */
	public static final String LOCATION_HEADRE_NAME = "rest-location";

	@SuppressWarnings("deprecation")
	@Override
	public void response(String location, HttpServletResponse response,HttpServletRequest request) {
		String data = JsonUtils.writeValueOrNull(ServerResponse.unmodifiableBody(302,"",location));
		response.setStatus(HttpStatus.PRECONDITION_REQUIRED.value());
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		response.addHeader("Access-Control-Expose-Headers",LOCATION_HEADRE_NAME);
		response.setHeader(LOCATION_HEADRE_NAME, location);
		try {
			ServletOutputStream out = response.getOutputStream();
			out.print(data);
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error("rest请求，重定向信息返回失败：{}",data,e);
		}
	}

}
